using System.Xml;
using Microsoft.Toolkit.Uwp.Notifications;
using Newtonsoft.Json;
using Timer = System.Windows.Forms.Timer;

namespace FuckJob.Winform
{
    public partial class Form1 : Form
    {

        private NotifyIcon notifyIcon;
        private ContextMenuStrip contextMenuStrip;

        private TimeSpan defaultStartTime = new(9, 0, 0);
        private TimeSpan defaultEndTime = new(17, 30, 0);
        private TimeSpan defaultLunchStartTime = new(11, 55, 0);

        public TimeSpan startTime;
        public TimeSpan endTime;
        public TimeSpan lunchStartTime;


        private bool hasNotifiedStartTime = false;  // 标记是否已通知上班时间
        private bool hasNotifiedLunchTime = false;  // 标记是否已通知午餐时间
        private bool hasNotifiedEndTime = false;    // 标记是否已通知下班时间

        private Timer timer;

        public Form1()
        {

            // InitializeComponent();

            // 初始化窗体属性，完全隐藏
            this.ShowInTaskbar = false; // 不显示在任务栏
            this.WindowState = FormWindowState.Minimized; // 最小化状态
            this.Opacity = 0; // 设置完全透明
            // 初始化时间设置，从配置文件读取
            InitializeSettingsFromFile();

            InitializeNotifyIcon();
            StartTimeChecking();
        }


        protected override CreateParams CreateParams
        {
            get
            {
                // 阻止窗体出现在 Alt+Tab 列表中
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x80; // WS_EX_TOOLWINDOW: 不显示在 Alt+Tab
                return cp;
            }
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_SHOWWINDOW = 0x18;
            if (m.Msg == WM_SHOWWINDOW)
            {
                // 阻止窗体响应显示消息
                return;
            }
            base.WndProc(ref m);
        }

        private void InitializeSettingsFromFile()
        {
            string filePath = "appsettings.json";

            var settings = new Settings();

            if (File.Exists(filePath))
            {
                try
                {
                    string json = File.ReadAllText(filePath);
                    settings = JsonConvert.DeserializeObject<Settings>(json);

                }
                catch
                {
                    MessageBox.Show("缺少配置文件，将使用默认时间。", "Error", MessageBoxButtons.OK);

                }
            }

            startTime = (settings?.StartTime != null && settings.StartTime != TimeSpan.Zero)
                           ? settings.StartTime
                           : defaultStartTime;

            endTime = (settings?.EndTime != null && settings.EndTime != TimeSpan.Zero)
                ? settings.EndTime
                : defaultEndTime;
            lunchStartTime = (settings?.LunchStartTime != null && settings.LunchStartTime != TimeSpan.Zero)
                ? settings.LunchStartTime
                : defaultLunchStartTime;


        }


        private void InitializeNotifyIcon()
        {
            notifyIcon = new NotifyIcon();
            notifyIcon.Icon = new Icon("icon.ico");  // 替换为您的图标文件

            contextMenuStrip = new ContextMenuStrip();
            ToolStripMenuItem settingMenuItem = new ToolStripMenuItem("设置");
            ToolStripMenuItem exitMenuItem = new ToolStripMenuItem("退出");
            settingMenuItem.Click += SettingMenuItem_Click;
            exitMenuItem.Click += ExitMenuItem_Click;
            contextMenuStrip.Items.Add(settingMenuItem);
            contextMenuStrip.Items.Add(exitMenuItem);

            notifyIcon.ContextMenuStrip = contextMenuStrip;
            notifyIcon.Visible = true;
        }


        private void SettingMenuItem_Click(object sender, EventArgs e)
        {
            using (SettingForm settingsForm = new SettingForm(this))
            {
                settingsForm.ShowDialog();
            }
        }

        private void ExitMenuItem_Click(object sender, EventArgs e)
        {

            Application.Exit(); // 退出程序

        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;

            TimeSpan currentTime = now.TimeOfDay;

            if (Math.Abs(currentTime.TotalMinutes - startTime.TotalMinutes) < 1 && !hasNotifiedStartTime)
            {
                ShowNotification("开始上班😢😢😢", EnumJob.Work);
                hasNotifiedStartTime = true;
            }

            TimeSpan fiveMinutesBeforeLunch = lunchStartTime.Subtract(new TimeSpan(0, 5, 0));

            if (!hasNotifiedLunchTime && currentTime >= fiveMinutesBeforeLunch && currentTime < lunchStartTime)
            {
                ShowNotification("不要再工作了，准备吃饭休息了！", EnumJob.Eat);
                hasNotifiedLunchTime = true;  // 标记已通知
            }


            // 下班前五分钟通知
            if (!hasNotifiedEndTime && currentTime >= endTime.Subtract(new TimeSpan(0, 5, 0)) && currentTime < endTime)
            {
                var tips = "要下班了；不要再工作了，再努力老板就开上劳斯莱斯了。";
                if (now.DayOfWeek == DayOfWeek.Friday)
                {
                    tips += " 周末快乐!";
                }

                ShowNotification(tips, EnumJob.Happy);
                hasNotifiedEndTime = true;  // 标记已通知
            }
        }

        private void StartTimeChecking()
        {
            if (timer == null)
            {
                timer = new Timer();
                timer.Interval = 60000;  // 每分钟检查一次
                timer.Tick += Timer_Tick;
                timer.Start();
            }

            // 每分钟检查一次是否需要重置通知标志
            Timer resetTimer = new Timer();
            resetTimer.Interval = 60000;  // 每分钟检查一次
            resetTimer.Tick += (sender, e) => ResetNotificationsAtMidnight();
            resetTimer.Start();
        }


        private void ResetNotificationsAtMidnight()
        {
            DateTime now = DateTime.Now;
            if (now.Hour == 0 && now.Minute == 0)
            {
                // 重置所有通知标志
                hasNotifiedStartTime = false;
                hasNotifiedLunchTime = false;
                hasNotifiedEndTime = false;
            }
        }


        private void ShowNotification(string message, EnumJob jobEnum)
        {
            var imgName = jobEnum switch
            {
                EnumJob.Eat => "eat.png",
                EnumJob.Work => "work.png",
                _ => "happy.png"
            };

            new ToastContentBuilder()
                .AddText(message)
                .AddInlineImage(new Uri(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "imgs", imgName)))
                .Show();
        }



    }
}
